<template>
  <div class="app-container">
    <!-- 移动端骨架屏 -->
    <mobile-skeleton 
      v-if="isMobile && loading" 
      :showHeader="true"
      :showCards="true"
      :cardsCount="3"
      :showPagination="false"
    />
    
    <!-- 桌面端布局 -->
    <div v-else-if="!isMobile">
      <h5>
        <img :src="backImg" style="width: 25px; height: 25px; cursor: pointer" @click="handleBack" />
      </h5>
      <h2 class="text-center">{{ paperData.name }}</h2>
      <p class="text-center" style="color: #666">{{ paperData.create_time }}</p>
  
      <el-row :gutter="24" style="margin-top: 50px">
        <el-col :span="4" class="text-center"> 考生姓名：{{ paperData.user }} </el-col>
        <el-col :span="4" class="text-center">
          试卷总分：{{ paperData.total_score }}分
        </el-col>
        <el-col :span="4" class="text-center">
          及格分数：{{ paperData.qualify_score }}分
        </el-col>
  
        <el-col :span="4" class="text-center" v-if="paperData.question !== undefined && paperData.question.length > 0">
          考试得分：{{
            (paperData.score * (100 /
              paperData.question.length)).toFixed(2) }}分
        </el-col>
        <el-col :span="4" class="text-center">
          考试结果：{{ paperData.is_passed | passedFilters }}
        </el-col>
      </el-row>
  
      <el-card style="margin-top: 20px">
        <div v-for="(item, index) in paperData.question" :key="item.id" class="qu-content">
          <!-- 题目 -->
          <p v-if="paperData.question !== undefined && paperData.question.length > 0"
            v-html="index + 1 + '.' + item.stem + '（得分：' + item.score * (100 / paperData.question.length).toFixed(1) + '分）'"
            class="paperData_title" />
          <p v-if="item.image != null && item.image != ''">
            <el-image :src="item.image" style="max-width: 100%" />
          </p>
          <!-- 单选 -->
          <div v-if="item.type == 1">
            <el-radio-group v-model="item.value[0]">
              <el-radio v-for="an in item.option" :label="an.id" :key="an.id">
                {{ an.name }}.{{ an.content }}
                <div v-if="an.image != null && an.image != ''" style="clear: both">
                  <el-image :src="an.image" style="max-width: 100%" />
                </div>
              </el-radio>
            </el-radio-group>
  
            <el-row :gutter="24">
              <el-col :span="12" style="color: #24da70">
                正确答案：{{ item.radioRight }}
              </el-col>
  
              <el-col v-show="item.answered == 0 || item.value.length == 0" :span="12"
                style="text-align: right; color: #ff0000">
                答题结果：未答
              </el-col>
  
              <el-col v-show="item.answered == 1 && item.value.length > 0 && item.is_right == 0" :span="12"
                style="text-align: right; color: #ff0000">
                答题结果：{{ item.myRadio }}
              </el-col>
  
              <el-col v-show="item.answered == 1 && item.value.length > 0 && item.is_right == 1" :span="12"
                style="text-align: right; color: #24da70">
                答题结果：{{ item.myRadio }}
              </el-col>
            </el-row>
          </div>
          <!-- 判断题 -->
          <div v-if="item.type == 3">
            <el-radio-group v-model="item.value">
              <el-radio :label="1">对 </el-radio>
              <el-radio :label="0">错 </el-radio>
            </el-radio-group>
            <el-row :gutter="24">
              <el-col :span="12" style="color: #24da70">
                正确答案：{{ item.answer | TrueFalesefilter }}
              </el-col>
  
              <el-col v-if="item.answered == 0 || item.value.length == 0" :span="12"
                style="text-align: right; color: #ff0000">
                答题结果：未答
              </el-col>
  
              <el-col v-if="item.answered == 1 && item.value.length !== 0 && item.value !== item.answer" :span="12"
                style="text-align: right; color: #ff0000">
                答题结果：{{ item.value | TrueFalesefilter }}
              </el-col>
  
              <el-col v-if="item.answered == 1 && item.value.length !== 0 && item.value == item.answer" :span="12"
                style="text-align: right; color: #24da70">
                答题结果：{{ item.value | TrueFalesefilter }}
              </el-col>
            </el-row>
          </div>
          <!-- 问答题 -->
          <div v-if="item.type == 4">
            <el-row :gutter="24">
              <el-col :span="12"> 我的回答：{{ item.value }} </el-col>
            </el-row>
          </div>
          <!-- 多选题 -->
          <div v-if="item.type == 2">
            <el-checkbox-group v-model="item.value">
              <el-checkbox v-for="an in item.option" :key="an.id" :label="an.id">{{ an.name }}.{{ an.content }}
                <div v-if="an.image != null && an.image != ''" style="clear: both">
                  <el-image :src="an.image" style="max-width: 100%" />
                </div>
              </el-checkbox>
            </el-checkbox-group>
  
            <el-row :gutter="24">
              <el-col :span="12" style="color: #24da70">
                正确答案：{{ multiRights[item.id].join('、') }}
              </el-col>
  
              <el-col v-if="item.answered == 0" :span="12" style="text-align: right; color: #ff0000">
                答题结果：未答
              </el-col>
  
              <el-col v-if="item.value.length !== 0 && !item.is_right && item.answered == 1" :span="12"
                style="text-align: right; color: #ff0000">
                答题结果：{{ myMulti[item.id].join('、') }}
              </el-col>
  
              <el-col v-if="item.value.length !== 0 && item.is_right && item.answered == 1" :span="12"
                style="text-align: right; color: #24da70">
                答题结果：{{ myMulti[item.id].join('、') }}
              </el-col>
            </el-row>
          </div>
        </div>
      </el-card>
    </div>
    
    <!-- 移动端布局 -->
    <div v-else class="mobile-paper-detail">
      <!-- 移动端头部 -->
      <div class="mobile-header">
        <img :src="backImg" style="width: 25px; height: 25px; cursor: pointer" @click="handleBack" />
        <span class="header-title" :style="{ color: theme }">考试详情</span>
      </div>
      
      <!-- 移动端考试信息卡片 -->
      <el-card class="paper-info-card" shadow="hover">
        <div class="paper-title">{{ paperData.name }}</div>
        <div class="paper-time">{{ paperData.create_time }}</div>
        
        <div class="user-info">
          <div class="info-item">
            <span class="label">考生姓名：</span>
            <span class="value">{{ paperData.user }}</span>
          </div>
          <div class="info-item">
            <span class="label">试卷总分：</span>
            <span class="value">{{ paperData.total_score }}分</span>
          </div>
          <div class="info-item">
            <span class="label">及格分数：</span>
            <span class="value">{{ paperData.qualify_score }}分</span>
          </div>
          <div class="info-item" v-if="paperData.question !== undefined && paperData.question.length > 0">
            <span class="label">考试得分：</span>
            <span class="value highlight" :style="{ color: theme }">
              {{ (paperData.score * (100 / paperData.question.length)).toFixed(2) }}分
            </span>
          </div>
          <div class="info-item">
            <span class="label">考试结果：</span>
            <span class="value" 
              :style="paperData.is_passed ? { color: '#67C23A' } : { color: '#F56C6C' }">
              {{ paperData.is_passed | passedFilters }}
            </span>
          </div>
        </div>
      </el-card>
      
      <!-- 移动端试题列表 -->
      <div class="question-list">
        <el-card 
          v-for="(item, index) in paperData.question" 
          :key="item.id" 
          class="question-card"
          shadow="hover">
          
          <!-- 试题标题 -->
          <div class="question-header">
            <span class="question-number">{{ index + 1 }}</span>
            <span class="question-type" :style="{ color: theme }">
              {{item.type == 1 ? '单选题' : item.type == 2 ? '多选题' : item.type == 3 ? '判断题' : '问答题'}}
            </span>
            <span class="question-score">{{ item.score * (100 / paperData.question.length).toFixed(1) }}分</span>
          </div>
          
          <!-- 试题内容 -->
          <div class="question-content">
            <p v-html="item.stem" class="question-stem"></p>
            <div v-if="item.image != null && item.image != ''" class="question-image">
              <el-image :src="item.image" style="max-width: 100%" />
            </div>
          </div>
          
          <!-- 选项与答案 -->
          <div class="question-answers">
            <!-- 单选题 -->
            <div v-if="item.type == 1" class="answer-section">
              <div class="options-list">
                <div v-for="an in item.option" :key="an.id" 
                  class="option-item"
                  :class="{
                    'correct-answer': item.answer[0] == an.id,
                    'wrong-answer': item.value[0] == an.id && item.value[0] != item.answer[0]
                  }">
                  <span class="option-name">{{ an.name }}. </span>
                  <span class="option-content" v-html="an.content"></span>
                  <div v-if="an.image" class="option-image">
                    <el-image :src="an.image" style="max-width: 100%" />
                  </div>
                </div>
              </div>
              
              <div class="answer-result">
                <div class="correct-answer">
                  <span class="label">正确答案：</span>
                  <span class="value">{{ item.radioRight }}</span>
                </div>
                
                <div class="user-answer" 
                  :class="{ 
                    'not-answered': item.answered == 0 || item.value.length == 0,
                    'wrong-answer': item.answered == 1 && item.value.length > 0 && item.is_right == 0,
                    'correct-answer': item.answered == 1 && item.value.length > 0 && item.is_right == 1
                  }">
                  <span class="label">我的答案：</span>
                  <span class="value" v-if="item.answered == 0 || item.value.length == 0">未答</span>
                  <span class="value" v-else>{{ item.myRadio }}</span>
                </div>
              </div>
            </div>
            
            <!-- 判断题 -->
            <div v-if="item.type == 3" class="answer-section">
              <div class="options-list judge-options">
                <div class="option-item" :class="{ 'correct-answer': item.answer == 1 }">
                  <span class="option-name">对</span>
                </div>
                <div class="option-item" :class="{ 'correct-answer': item.answer == 0 }">
                  <span class="option-name">错</span>
                </div>
              </div>
              
              <div class="answer-result">
                <div class="correct-answer">
                  <span class="label">正确答案：</span>
                  <span class="value">{{ item.answer | TrueFalesefilter }}</span>
                </div>
                
                <div class="user-answer" 
                  :class="{ 
                    'not-answered': item.answered == 0 || item.value.length == 0,
                    'wrong-answer': item.answered == 1 && item.value.length !== 0 && item.value !== item.answer,
                    'correct-answer': item.answered == 1 && item.value.length !== 0 && item.value == item.answer
                  }">
                  <span class="label">我的答案：</span>
                  <span class="value" v-if="item.answered == 0 || item.value.length == 0">未答</span>
                  <span class="value" v-else>{{ item.value | TrueFalesefilter }}</span>
                </div>
              </div>
            </div>
            
            <!-- 问答题 -->
            <div v-if="item.type == 4" class="answer-section">
              <div class="essay-answer">
                <span class="label">我的回答：</span>
                <div class="value">{{ item.value || '未作答' }}</div>
              </div>
            </div>
            
            <!-- 多选题 -->
            <div v-if="item.type == 2" class="answer-section">
              <div class="options-list">
                <div v-for="an in item.option" :key="an.id" 
                  class="option-item"
                  :class="{
                    'correct-answer': item.answer.includes(an.id),
                    'wrong-answer': item.value.includes(an.id) && !item.answer.includes(an.id)
                  }">
                  <span class="option-name">{{ an.name }}. </span>
                  <span class="option-content" v-html="an.content"></span>
                  <div v-if="an.image" class="option-image">
                    <el-image :src="an.image" style="max-width: 100%" />
                  </div>
                </div>
              </div>
              
              <div class="answer-result">
                <div class="correct-answer">
                  <span class="label">正确答案：</span>
                  <span class="value">{{ multiRights[item.id].join('、') }}</span>
                </div>
                
                <div class="user-answer" 
                  :class="{ 
                    'not-answered': item.answered == 0,
                    'wrong-answer': item.value.length !== 0 && !item.is_right && item.answered == 1,
                    'correct-answer': item.value.length !== 0 && item.is_right && item.answered == 1
                  }">
                  <span class="label">我的答案：</span>
                  <span class="value" v-if="item.answered == 0">未答</span>
                  <span class="value" v-else>{{ myMulti[item.id].join('、') || '未作答' }}</span>
                </div>
              </div>
            </div>
          </div>
        </el-card>
      </div>
      
      <!-- 返回按钮 -->
      <div class="mobile-action-container">
        <el-button type="primary" @click="handleBack" :style="{
          backgroundColor: theme,
          borderColor: theme
        }">返回</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import { paperResult } from "@/api/vadmin/exam/exam";
import backImg from "@/assets/images/back.png";
import { mapGetters, mapState } from "vuex";
import variables from "@/assets/styles/variables.scss";
import MobileSkeleton from "@/components/MobileSkeleton";
import "@/assets/styles/mobile/exam.scss";

export default {
  name: "results",
  components: { MobileSkeleton },
  data() {
    return {
      backImg: backImg,
      // 试卷ID
      paperId: "",
      loading: true,
      paperData: {
        quList: [],
      },
      radioValues: {},
      multiValues: {},
      radioRights: {},
      multiRights: {},
      myRadio: {},
      myMulti: {},
      isMobile: false,
      mediaQueryList: null,
    };
  },
  
  computed: {
    ...mapState(["settings"]),
    variables() {
      return variables;
    },
    theme() {
      return this.$store.state.settings.theme;
    },
  },

  filters: {
    TrueFalesefilter(val) {
      if (val == 0) {
        return "错";
      } else {
        return "对";
      }
    },
    passedFilters(val) {
      if (val == true) {
        return "合格";
      } else {
        return "不合格";
      }
    },
  },

  created() {
    const id = this.$route.params.id;
    if (typeof id !== "undefined") {
      this.paperId = id;
      this.fetchData(id);
    }
  },

  mounted() {
    // 使用媒体查询API直接监听视口变化
    this.mediaQueryList = window.matchMedia('(max-width: 767px)');
    
    // 初始化isMobile状态
    this.isMobile = this.mediaQueryList.matches;
    
    // 为媒体查询添加监听器
    const handleMediaChange = (e) => {
      this.isMobile = e.matches;
      
      // 强制组件重新渲染
      this.$forceUpdate();
    };
    
    // 使用适当的API添加监听器
    if (this.mediaQueryList.addEventListener) {
      this.mediaQueryList.addEventListener('change', handleMediaChange);
    } else {
      // 旧版浏览器支持
      this.mediaQueryList.addListener(handleMediaChange);
    }
    
    // 存储监听器以便后续移除
    this.mediaChangeHandler = handleMediaChange;
  },
  
  beforeDestroy() {
    // 移除媒体查询监听器
    if (this.mediaQueryList) {
      if (this.mediaQueryList.removeEventListener) {
        this.mediaQueryList.removeEventListener('change', this.mediaChangeHandler);
      } else {
        // 旧版浏览器支持
        this.mediaQueryList.removeListener(this.mediaChangeHandler);
      }
    }
  },

  methods: {
    handleBack() {
      this.$router.back()//返回浏览器上一页，并保留上一页数据
    },
    fetchData(id) {
      paperResult(id).then((response) => {
        // 试卷内容
        this.paperData = response;
        // 填充该题目的答案
        this.paperData.question.forEach((item) => {
          const multiRight = [];
          const myMulti = [];

          item.option.forEach((an) => {
            if (item.type == 1) {
              //单选题
              if (item.value[0] == an.id) {
                item.myRadio = an.name; //用户选择
              }
              if (item.answer[0] == an.id) {
                item.radioRight = an.name; //正确选择
              }
            } else if (item.type == 2) {
              //多选题
              // item.answer.push(an.id)
              // item.value.push(an.abc)

              item.answer.forEach((a) => {
                if (a == an.id) {
                  multiRight.push(an.name);
                }
              });
              item.value.forEach((b) => {
                if (b == an.id) {
                  myMulti.push(an.name);
                }
              });
            }
            this.myMulti[item.id] = myMulti;
            this.multiRights[item.id] = multiRight;
          });
        });
        this.loading = false;
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.qu-content {
  border-bottom: #eee 1px solid;
  padding-bottom: 10px;
}

.qu-content div {
  line-height: 30px;
}

.el-checkbox-group label,
.el-radio-group label {
  width: 100%;
}

.card-title {
  background: #eee;
  line-height: 35px;
  text-align: center;
  font-size: 14px;
}

.card-line {
  padding-left: 10px;
}

.card-line span {
  cursor: pointer;
  margin: 2px;
}

.paperData_title {
  display: flex;
  align-items: center;
}

.passedColor {
  color: #ffad45;
}

.no_passedColor {
  color: red;
}

/* 移动端样式 */
.mobile-paper-detail {
  padding: 0 5px;
  padding-bottom: 70px;
}

.mobile-header {
  display: flex;
  align-items: center;
  padding: 10px;
  margin-bottom: 15px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
}

.header-title {
  font-size: 18px;
  font-weight: bold;
  margin-left: 10px;
}

.paper-info-card {
  margin-bottom: 15px;
  border-radius: 8px;
}

.paper-title {
  font-size: 18px;
  font-weight: bold;
  text-align: center;
  margin-bottom: 5px;
}

.paper-time {
  font-size: 12px;
  color: #909399;
  text-align: center;
  margin-bottom: 15px;
}

.user-info {
  background-color: #f8f9fa;
  border-radius: 6px;
  padding: 10px 15px;
}

.info-item {
  margin-bottom: 8px;
  display: flex;
  align-items: center;
}

.label {
  color: #606266;
  min-width: 80px;
}

.value {
  flex: 1;
  color: #303133;
}

.highlight {
  font-weight: bold;
  font-size: 16px;
}

.question-list {
  margin-bottom: 15px;
}

.question-card {
  margin-bottom: 15px;
  border-radius: 8px;
}

.question-header {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  padding-bottom: 10px;
  border-bottom: 1px solid #f0f0f0;
}

.question-number {
  background-color: #f0f0f0;
  width: 24px;
  height: 24px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  margin-right: 10px;
}

.question-type {
  font-size: 14px;
  font-weight: bold;
  flex: 1;
}

.question-score {
  color: #f56c6c;
  font-size: 14px;
}

.question-content {
  margin-bottom: 15px;
}

.question-stem {
  margin: 0;
  line-height: 1.5;
}

.question-image {
  margin-top: 10px;
}

.answer-section {
  background-color: #f8f9fa;
  border-radius: 6px;
  padding: 10px;
}

.options-list {
  margin-bottom: 15px;
}

.option-item {
  padding: 8px;
  margin-bottom: 8px;
  border-radius: 4px;
  background-color: #fff;
  border: 1px solid #ebeef5;
}

.option-name {
  font-weight: bold;
  margin-right: 5px;
}

.option-content {
  line-height: 1.5;
}

.option-image {
  margin-top: 5px;
}

.answer-result {
  border-top: 1px dashed #ebeef5;
  padding-top: 10px;
}

.correct-answer {
  color: #67c23a;
  margin-bottom: 8px;
  border-left: 3px solid #67c23a;
  padding-left: 8px;
}

.wrong-answer {
  color: #f56c6c;
  border-left: 3px solid #f56c6c;
  padding-left: 8px;
}

.not-answered {
  color: #f56c6c;
  border-left: 3px solid #f56c6c;
  padding-left: 8px;
}

.user-answer {
  margin-top: 5px;
}

.essay-answer {
  padding: 10px;
  background-color: #fff;
  border-radius: 4px;
  
  .label {
    display: block;
    margin-bottom: 5px;
    color: #303133;
  }
  
  .value {
    white-space: pre-wrap;
    word-break: break-all;
    line-height: 1.5;
  }
}

.judge-options {
  display: flex;
  
  .option-item {
    flex: 1;
    text-align: center;
    margin-right: 10px;
    
    &:last-child {
      margin-right: 0;
    }
  }
}
</style>
